package cc.admin.modules.graduate.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.aspect.annotation.AutoLog;
import cc.admin.common.sys.base.controller.BaseController;
import cc.admin.common.sys.query.QueryGenerator;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.modules.graduate.entity.*;
import cc.admin.modules.graduate.entity.DTO.DesignQuestionsListDto;
import cc.admin.modules.graduate.mapper.DesignAnswerListMapper;
import cc.admin.modules.graduate.mapper.DesignAnswerMapper;
import cc.admin.modules.sys.entity.SysCascade;
import cc.admin.modules.sys.service.ISysCascadeService;
import cc.admin.modules.graduate.service.IDesignQuestionsListService;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 算法设计与分析题主表
 * @Author: cc-admin
 * @Date: 2025-01-03
 * @Version: V1.0.0
 */
@Slf4j
@Api(tags = "算法设计与分析题主表")
@RestController
@RequestMapping("/design/questionsList")
public class DesignQuestionsListController extends BaseController<DesignQuestionsListDto, IDesignQuestionsListService> {
    @Autowired
    private IDesignQuestionsListService designQuestionsListService;

    @Autowired
    private DesignAnswerListMapper designAnswerListMapper;

    @Autowired
    private DesignAnswerMapper designAnswerMapper;


    /**
     * 分页列表查询
     *
     * @param key
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-分页列表查询")
    @ApiOperation(value = "算法设计与分析题主表-分页列表查询", notes = "算法设计与分析题主表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(
            @RequestParam(name = "key", required = false) String key,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        QueryWrapper<DesignQuestionsListDto> queryWrapper = QueryGenerator.initQueryWrapper(new DesignQuestionsListDto(), req.getParameterMap());
        if (StrUtil.isNotEmpty(key)) {
            queryWrapper.like("question_stem",key);
        }
        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");
        String tab = catalogs[0];
        queryWrapper.eq("major_id", tab);

        Page<DesignQuestionsListDto> page = new Page<DesignQuestionsListDto>(pageNo, pageSize);
        IPage<DesignQuestionsListDto> pageList = designQuestionsListService.page(page, queryWrapper);

        pageList.getRecords().forEach(designQuestionsListDto -> {
            //把问题集合放入对象
            List<DesignQuestions> designQuestionsList = designQuestionsListService.getchildQuestions(designQuestionsListDto.getChildIds());
            designQuestionsListDto.setQuestionList(designQuestionsList);
            //把问题分类放对象
            ArrayList<Category> categories = new ArrayList<>();
            //当存在下拉数据时
            if (designQuestionsListDto.getCategoryIds() != null && designQuestionsListDto.getCategoryIdsText() != null) {
                String[] split = designQuestionsListDto.getCategoryIds().split(",");
                String[] split2 = designQuestionsListDto.getCategoryIdsText().split(",");
                for (int i = 0; i < split.length; i++) {
                    Category category = new Category(split[i], split2[i]);
                    categories.add(category);
                }
            }
            designQuestionsListDto.setCategorys(categories);
        });

        return Result.ok(pageList);
    }

    public DesignQuestionsListDto setCategory(DesignQuestionsListDto designQuestionsListDto) {
        List<Category> categorys = designQuestionsListDto.getCategorys();
        ArrayList<String> categoryIds = new ArrayList<>();
        ArrayList<String> categoryIdsText = new ArrayList<>();
        categorys.forEach(category -> {
            categoryIds.add(category.getValue());
            categoryIdsText.add(category.getLabel());
        });
        designQuestionsListDto.setCategoryIds(String.join(",", categoryIds));
        designQuestionsListDto.setCategoryIdsText(String.join(",", categoryIdsText));

        return designQuestionsListDto;
    }

    /**
     * 添加
     *
     * @param designQuestionsList
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-添加")
    @ApiOperation(value = "算法设计与分析题主表-添加", notes = "算法设计与分析题主表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody DesignQuestionsListDto designQuestionsList) {
        String objectId = IdUtil.objectId();
        designQuestionsList.setId(objectId);
        String childIds = designQuestionsListService.saveDesignQuestions(designQuestionsList, objectId);
        designQuestionsList.setChildIds(childIds);
        designQuestionsList = setCategory(designQuestionsList);
        designQuestionsListService.save(designQuestionsList);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param designQuestionsList
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-编辑")
    @ApiOperation(value = "算法设计与分析题主表-编辑", notes = "算法设计与分析题主表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody DesignQuestionsListDto designQuestionsList) {
        designQuestionsList = setCategory(designQuestionsList);

        designQuestionsListService.updateChild(designQuestionsList);
//        designQuestionsListService.updateById(designQuestionsList);
        return Result.ok("编辑成功!");
    }


    /**
     * 复制
     *
     * @param id
     * @param name
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-复制")
    @ApiOperation(value = "算法设计与分析题主表-复制", notes = "算法设计与分析题主表-复制")
    @PostMapping(value = "/copy")
    public Result<?> copy(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "name", required = true) String name) {
        DesignQuestionsListDto designQuestionsList = designQuestionsListService.getById(id);
        designQuestionsList.setId(IdUtil.fastUUID());
        designQuestionsList.setCreateTime(new Date());
        designQuestionsListService.save(designQuestionsList);
        return Result.ok("复制成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-通过id删除")
    @ApiOperation(value = "算法设计与分析题主表-通过id删除", notes = "算法设计与分析题主表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        designQuestionsListService.removeselfAndChild(id);
        return Result.ok("删除成功!");
    }

    @AutoLog(value = "算法设计与分析题主表-通过id删除")
    @ApiOperation(value = "算法设计与分析题主表-通过id删除", notes = "算法设计与分析题主表-通过id删除")
    @DeleteMapping(value = "/deleteAnswer")
    public Result<?> deleteDesignAnswer(@RequestParam(name = "id", required = true) String id) {
        designAnswerListMapper.deleteById(id);
        LambdaQueryWrapper<DesignAnswer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DesignAnswer::getParentId, id);
        designAnswerMapper.delete(queryWrapper);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-批量删除")
    @ApiOperation(value = "算法设计与分析题主表-批量删除", notes = "算法设计与分析题主表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.designQuestionsListService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-批量删除")
    @ApiOperation(value = "算法设计与分析题主表-批量删除", notes = "算法设计与分析题主表-批量删除")
    @DeleteMapping(value = "/deleteAnswerBatch")
    public Result<?> deleteAnswerBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        designAnswerListMapper.deleteBatchIds(list);
        LambdaQueryWrapper<DesignAnswer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(DesignAnswer::getParentId, list);
        designAnswerMapper.delete(queryWrapper);
        return Result.ok("批量删除成功！");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "算法设计与分析题主表-通过id查询")
    @ApiOperation(value = "算法设计与分析题主表-通过id查询", notes = "算法设计与分析题主表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        DesignQuestionsListDto designQuestionsList = designQuestionsListService.getById(id);
        return Result.ok(designQuestionsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(@RequestParam(name="choiceQuestions",required = false) String choiceQuestionIds,@RequestParam(name="key",required = false) String key,@RequestParam(name="catalog",required = false) String catalog,HttpServletRequest request) {

        return designQuestionsListService.exportXls(request, choiceQuestionIds,catalog, DesignQuestionsListDto.class, "材料题");
    }

    /*
    * 下载模板
    * */
    @GetMapping(value = "/exportModelXls")
    public ModelAndView exportModelXls() {

        return designQuestionsListService.exportXlsModel(exportDesignModel.class, "导入");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return designQuestionsListService.importExcel(request, response, DesignQuestionsListDto.class);
    }

    @RequestMapping(value = "/getErrorDesign", method = RequestMethod.GET)
    public Result<?> getErrorDesign(@RequestParam(name = "key", required = false) String key,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {


        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");
        String tab = catalogs[0];


        List<DesignAnswerList> errorDesign = designQuestionsListService.getErrorDesign(tab,key);

        Page<DesignAnswerList> page = new Page<DesignAnswerList>(pageNo, pageSize);
//		IPage<DesignAnswerList> pageList = .page(page, queryWrapper);
//		pageList.setRecords(errorDesign);
        // 设置总记录数
        page.setTotal(errorDesign.size());

// 计算分页数据的起始位置和结束位置
        int start = (pageNo - 1) * pageSize;
        int end = Math.min(start + pageSize, errorDesign.size());

// 截取当前页的数据
        List<DesignAnswerList> pageData = errorDesign.subList(start, end);

// 将分页数据设置到 Page 对象中
        page.setRecords(pageData);
        return Result.ok(errorDesign);
    }


    @RequestMapping(value = "/getNoVideoDesign", method = RequestMethod.GET)
    public Result<?> getNoVideoDesign(@RequestParam(name = "key", required = false) String key,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {


        Map<String, String[]> parameterMap = req.getParameterMap();
        String[] catalogs = parameterMap.get("catalog");
        String tab = catalogs[0];


        List<DesignQuestionsListDto> errorDesign = designQuestionsListService.getNoVideoDesign(tab);

        Page<DesignQuestionsListDto> page = new Page<DesignQuestionsListDto>(pageNo, pageSize);
        // 设置总记录数
        page.setTotal(errorDesign.size());

// 计算分页数据的起始位置和结束位置
        int start = (pageNo - 1) * pageSize;
        int end = Math.min(start + pageSize, errorDesign.size());

// 截取当前页的数据
        List<DesignQuestionsListDto> pageData = errorDesign.subList(start, end);

// 将分页数据设置到 Page 对象中
        page.setRecords(pageData);
        return Result.ok(errorDesign);
    }

}
